# coding: utf-8
from typing import Dict

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget, QVBoxLayout, QStackedWidget
from loguru import logger
from qfluentwidgets import SearchLineEdit, Pivot, SegmentedWidget

from ...common import pluginManager, SearchResultModel, APIBase
from ...components import GridLayout, HorizontalScrollArea, queue_thread_manager, ComicCard, VerticalScrollArea


class SearchInterface(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self)
        self.search_line_edit = SearchLineEdit(self)
        self.pivotScrollArea = HorizontalScrollArea(self)
        self.pivot = SegmentedWidget(self)
        self.stackedWidget = QStackedWidget(self)

        self.interfaces = {}  # type: Dict[str, QWidget]
        self.key = ''

        self.__initWidgets()
        self.__initLayout()
        self.__connectSignals()

    def __initWidgets(self):
        self.setObjectName("SearchInterface")
        self.search_line_edit.searchButton.setShortcut("Return")
        self.search_line_edit.setPlaceholderText("请输入搜索内容")

        self.loadPlugins()

    def __initLayout(self):
        self.pivotScrollArea.setFixedHeight(30)
        self.pivotScrollArea.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.pivot.layout().setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.pivotScrollArea.setWidget(self.pivot)

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.search_line_edit)
        self.verticalLayout.addWidget(self.pivotScrollArea)
        self.verticalLayout.addWidget(self.stackedWidget)

    def __connectSignals(self):
        self.search_line_edit.searchSignal.connect(self.onSearch)
        self.pivot.currentItemChanged.connect(self.onPivotChanged)

    def loadPlugins(self):
        self.clear()
        plugins = pluginManager.values()
        for plugin in plugins:
            self.addSubInterface(plugin)
        self.pivot.setCurrentItem(plugins[0].name)
        self.pivot.setItemFontSize(14)

    def onSearch(self, text: str):
        if not text:
            return
        logger.info(f"搜索文本: {text}")
        route_key = self.pivot.currentRouteKey()
        plugin = pluginManager.get(route_key)
        if not plugin:
            return
        queue_thread_manager.send_function(plugin.search, text, slot=self.onSearchFinished)

    def onSearchFinished(self, result: SearchResultModel):
        comics = result.comicList
        widget:VerticalScrollArea = self.interfaces[self.pivot.currentRouteKey()]
        widget.setProperty('keyword', result.keyword)
        layout: GridLayout = widget.widget().layout()
        layout.takeAllWidgets()
        for comic in comics:
            card = ComicCard(widget)
            card.setModel(comic)
            layout.addWidget(card)

    def addSubInterface(self, plugin: APIBase):
        name = plugin.name
        widget = VerticalScrollArea(self.stackedWidget)
        sub_widget = QWidget(widget)
        sub_widget.setLayout(GridLayout(widget))
        sub_widget.layout().setItemMinimumWidth(150)
        widget.setWidget(sub_widget)
        widget.setObjectName(name)
        self.interfaces[name] = widget
        self.stackedWidget.addWidget(widget)
        self.pivot.addItem(routeKey=name, text=name, icon=plugin.icon)

    def clear(self):
        self.interfaces.clear()
        self.pivot.clear()
        for widget in self.interfaces.values():
            self.stackedWidget.removeWidget(widget)
            widget.deleteLater()

    def onPivotChanged(self, key: str):
        logger.info(f"搜索页面, 切换到 {key} 页面")
        widget = self.interfaces.get(key)
        if not widget:
            return
        keyword = widget.property('keyword')
        self.stackedWidget.setCurrentWidget(widget)
        old = self.search_line_edit.text().strip()
        if not keyword or keyword != old:
            self.onSearch(old)
